<?php

	// get request time
	$time = time();

	// check number of params and param names
	if (sizeof($_POST) != 5 || !array_key_exists('appkey', $_POST) || !array_key_exists('hdvid', $_POST) || !array_key_exists('lat', $_POST) || !array_key_exists('lon', $_POST) || !array_key_exists('acc', $_POST)) 
	{
		echo "Usage!";
		exit();
	}

	// if passed then check whether strlen appkey & hdvid == 40
	if (strlen(trim($_POST['appkey'])) != 40 || strlen(trim($_POST['hdvid'])) != 40)
	{
		echo "Size!";
		exit();
	}

	// if passed then validate numeric params
	if (!is_numeric($_POST['lat']) || !is_numeric($_POST['lon']) || !is_numeric($_POST['acc']))
	{
		echo "Not numeric!";
		exit();
	}

	// if passed then connect to db and define variables;
	$mysqli = new mysqli('localhost', 'root', 'project3', 'implauth');
	if ($mysqli->connect_errno)
	{
		echo "Database connection error!";
		exit();
	}
	$appkey = $_POST['appkey'];
	$hdvid = $_POST['hdvid'];
	$lat = $_POST['lat'];
	$lon = $_POST['lon'];
	$acc = $_POST['acc'];

	// if passed then validate appkey and hdvid
	$res = $mysqli->query("select count(*) as total from hdvid_appkey where hdvid like '$hdvid' and appkey like '$appkey'");
	$ob = $res->fetch_object();
	$res->close();
	if ($ob->total != 1)
	{
		echo 1;
		$mysqli->close();
		exit();
	}

	// if passed then update OR insert, then echo 0;
	$mysqli->query("update locations set latitude = $lat, longitude = $lon, accuracy = $acc, time = $time where hdeviceid like '$hdvid'");
	$affrows = $mysqli->affected_rows;
	if ($affrows == 1)
	{
		echo 0;
		$mysqli->close();
		exit();
	}
	if ($affrows == 0)
	{
		$mysqli->query("insert into locations values('$hdvid', $lat, $lon, $acc, $time, 'n')");
		if ($mysqli->affected_rows == 0)
		{
			echo "Error: insertion failed!";
		}
		else
		{
			echo 0;
		}
		$mysqli->close();
		exit();
	}
	echo 2;
	$mysqli->close();

?>
